package com.ruoyi.operation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ssh.Sftp;
import com.alibaba.excel.ExcelReader;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.excel.utils.ExcelUtil;
import com.ruoyi.common.mybatis.core.page.PageQuery;
import com.ruoyi.common.mybatis.core.page.TableDataInfo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.operation.common.CommonVariable;
import com.ruoyi.operation.domain.bo.THKDateBo;
import com.ruoyi.operation.properties.FtpProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.operation.domain.bo.TExchangerateBo;
import com.ruoyi.operation.domain.vo.TExchangerateVo;
import com.ruoyi.operation.domain.TExchangerate;
import com.ruoyi.operation.mapper.TExchangerateMapper;
import com.ruoyi.operation.service.ITExchangerateService;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 来自finchina的汇率Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-22
 */
@RequiredArgsConstructor
@Service
public class TExchangerateServiceImpl implements ITExchangerateService {

    private final TExchangerateMapper baseMapper;

    private final FtpProperties ftpProperties;

    /**
     * 查询来自finchina的汇率
     */
    @Override
    public TExchangerateVo queryById(String natureday){
        return baseMapper.selectVoById(natureday);
    }

    /**
     * 查询来自finchina的汇率列表
     */
    @Override
    public TableDataInfo<TExchangerateVo> queryPageList(TExchangerateBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TExchangerate> lqw = buildQueryWrapper(bo);
        Page<TExchangerateVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询来自finchina的汇率列表
     */
    @Override
    public List<TExchangerateVo> queryList(TExchangerateBo bo) {
        LambdaQueryWrapper<TExchangerate> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TExchangerate> buildQueryWrapper(TExchangerateBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TExchangerate> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getNatureday()), TExchangerate::getNatureday, bo.getNatureday());
        lqw.eq(StringUtils.isNotBlank(bo.getOriginalcurrency()), TExchangerate::getOriginalcurrency, bo.getOriginalcurrency());
        lqw.eq(StringUtils.isNotBlank(bo.getValuationcurrency()), TExchangerate::getValuationcurrency, bo.getValuationcurrency());
        lqw.eq(bo.getExchangerate() != null, TExchangerate::getExchangerate, bo.getExchangerate());
        return lqw;
    }

    /**
     * 新增来自finchina的汇率
     */
    @Override
    public Boolean insertByBo(TExchangerateBo bo) {
        TExchangerate add = BeanUtil.toBean(bo, TExchangerate.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setNatureday(add.getNatureday());
        }
        return flag;
    }

    /**
     * 修改来自finchina的汇率
     */
    @Override
    public Boolean updateByBo(TExchangerateBo bo) {
        TExchangerate update = BeanUtil.toBean(bo, TExchangerate.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TExchangerate entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除来自finchina的汇率
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public R<String> getFtpFile(String path) {
        Sftp sftp = new Sftp(ftpProperties.getHost(), ftpProperties.getPort(), ftpProperties.getUsername(), ftpProperties.getPassword());
        return R.ok();
    }

    @Override
    public R<String> executeStepDate(THKDateBo thkDateBo) {
        String path = thkDateBo.getBasePath();
        switch (thkDateBo.getStepType()){
            case CommonVariable.EXCHANGE_RATE:
                String exchangeRatePath = path+"LSFA_EXCHANGERATE_"+thkDateBo.getStepDate()+".CSV";
                return insertDataByCsv(exchangeRatePath,thkDateBo.getStepDate());
            case CommonVariable.ESTIMATE_DATA:
                String estimatePath = path+"LSFA_ESTIMATE_"+thkDateBo.getStepDate()+".CSV";
                return insertEstimateData(estimatePath,thkDateBo.getStepDate());
            case CommonVariable.FINAL_DATA:
                return insertFinalData(thkDateBo.getBasePath(),thkDateBo.getStepDate());
            case CommonVariable.CSV_DATA:
                return getFtpFile(thkDateBo.getBasePath());
            case CommonVariable.COUNT_DATA:
                return countData(thkDateBo.getStepDate());
            default:
                return R.fail("未知步骤");
        }
    }

    public R<String> countData(String stepDate) {
        return null;
    }

    public R<String> insertFinalData(String basePath, String stepDate) {
        return null;
    }

    public R<String> insertDataByCsv(String csvFilePath,String date) {
        try (InputStream fileInputStream = new FileInputStream(csvFilePath)){
            List<TExchangerate> importExcel = ExcelUtil.importExcel(fileInputStream, TExchangerate.class)
                .stream().filter(item->item.getIndex().equals("0001")).collect(Collectors.toList());
            LambdaQueryWrapper<TExchangerate> lqw = new LambdaQueryWrapper<>();
            lqw.eq(TExchangerate::getNatureday, date);
            baseMapper.delete(lqw);
            return baseMapper.insertBatch(importExcel)?R.ok():R.fail();
        } catch (FileNotFoundException e) {
            return R.fail("文件不存在");
        } catch (IOException e) {
            return R.fail("文件读取异常");
        }
    }
    public R<String> insertEstimateData(String estimatePath, String stepDate) {
        return null;
    }
}
